import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import type { DictType, DictTypeQuery, CreateDictType, UpdateDictType } from '@/types/api/config/dictType'
import type { DictData, DictDataQuery, CreateDictData, UpdateDictData } from '@/types/api/config/dictData'
import { 
  getDictTypePage, 
  getDictTypeDetail, 
  createDictType, 
  updateDictType, 
  deleteDictType, 
  batchDeleteDictType, 
  exportDictType,
  getDictDataPage, 
  getDictDataDetail, 
  createDictData, 
  updateDictData, 
  deleteDictData, 
  batchDeleteDictData, 
} from '@/api/config/dict'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import type dayjs from 'dayjs'

export const useDictStore = defineStore('dict', () => {
  const { t } = useI18n()

  // ------------ 基础状态 ------------
  // 当前选中的字典类型
  const currentDictType = ref<string>('')
  const currentDictTypeName = ref<string>('')
  
  // 当前编辑的记录ID
  const currentTypeId = ref<string>('')
  const currentDataId = ref<string>('')
  
  // ------------ 加载状态 ------------
  const typeLoading = ref(false)
  const typeSubmitLoading = ref(false)
  const dataLoading = ref(false)
  const dataSubmitLoading = ref(false)
  
  // ------------ 字典类型相关状态 ------------
  // 字典类型数据列表
  const typeList = ref<DictType[]>([])
  
  // 字典类型分页
  const typePagination = reactive<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total) => `共 ${total} 条`
  })
  
  // 字典类型查询参数
  const typeQueryParams = reactive<DictTypeQuery>({
    dictName: '',
    dictType: '',
    status: undefined,
    pageNum: 1,
    pageSize: 10
  })
  
  // 日期范围
  const createTimeRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | undefined>(undefined)
  
  // 弹窗状态
  const typeModalVisible = ref(false)
  
  // 表单数据
  const typeFormData = reactive<CreateDictType>({
    dictName: '',
    dictType: '',
    status: '0',
    remark: ''
  })
  
  // 表单模式
  const typeFormMode = ref<'add' | 'edit'>('add')
  
  // 表单标题
  const typeFormTitle = computed(() => typeFormMode.value === 'add' ? t('dict.addType') : t('dict.editType'))
  
  // ------------ 字典数据相关状态 ------------
  // 字典数据列表
  const dataList = ref<DictData[]>([])
  
  // 字典数据分页
  const dataPagination = reactive<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total) => `共 ${total} 条`
  })
  
  // 字典数据查询参数
  const dataQueryParams = reactive<DictDataQuery>({
    dictType: '',
    dictLabel: '',
    dictValue: '',
    status: undefined,
    pageNum: 1,
    pageSize: 10
  })
  
  // 弹窗状态
  const dataModalVisible = ref(false)
  
  // 表单数据
  const dataFormData = reactive<CreateDictData>({
    dictType: '',
    dictLabel: '',
    dictValue: '',
    dictSort: 0,
    status: '0',
    cssClass: '',
    remark: ''
  })
  
  // 表单模式
  const dataFormMode = ref<'add' | 'edit'>('add')
  
  // 表单标题
  const dataFormTitle = computed(() => dataFormMode.value === 'add' ? t('dict.addData') : t('dict.editData'))

  // ------------ 字典类型方法 ------------
  /**
   * 获取字典类型列表
   */
  const fetchTypeList = async () => {
    try {
      typeLoading.value = true
      
      // 构建查询参数
      const params: DictTypeQuery = {
        ...typeQueryParams,
        // 处理日期范围
        ...(createTimeRange.value && createTimeRange.value.length === 2
          ? {
              beginTime: createTimeRange.value[0]?.format('YYYY-MM-DD'),
              endTime: createTimeRange.value[1]?.format('YYYY-MM-DD')
            }
          : {})
      }
      
      const res = await getDictTypePage(params)
      
      if (res.code === 200) {
        typeList.value = res.data.list
        typePagination.total = res.data.total
      } else {
        message.error(res.message || t('dict.loadFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
    } finally {
      typeLoading.value = false
    }
  }

  /**
   * 获取字典类型详情
   * @param id 字典类型ID
   */
  const fetchTypeDetail = async (id: string) => {
    try {
      const res = await getDictTypeDetail(id)
      
      if (res.code === 200) {
        Object.assign(typeFormData, res.data)
        typeFormMode.value = 'edit'
        typeModalVisible.value = true
      } else {
        message.error(res.message || t('dict.detailFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchDetailFailed'))
    }
  }

  /**
   * 提交字典类型表单
   */
  const submitTypeForm = async () => {
    typeSubmitLoading.value = true
    try {
      let result
      if (typeFormMode.value === 'add') {
        result = await createDictType(typeFormData)
      } else {
        // 编辑模式需要添加id属性，转为UpdateDictType类型
        const updateData: UpdateDictType = {
          ...typeFormData,
          id: currentTypeId.value
        }
        result = await updateDictType(currentTypeId.value, updateData)
      }
      
      if (result.code === 200) {
        message.success(typeFormMode.value === 'add' ? t('common.createSuccess') : t('common.updateSuccess'))
        typeModalVisible.value = false
        await fetchTypeList()
        return true
      } else {
        message.error(result.message || t('common.operationFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.operationFailed'))
      return false
    } finally {
      typeSubmitLoading.value = false
    }
  }

  /**
   * 删除字典类型
   * @param id 字典类型ID
   */
  const removeType = async (id: string) => {
    try {
      const res = await deleteDictType(id)
      
      if (res.code === 200) {
        message.success(t('common.deleteSuccess'))
        fetchTypeList()
        return true
      } else {
        message.error(res.message || t('common.deleteFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.deleteFailed'))
      return false
    }
  }

  /**
   * 批量删除字典类型
   * @param ids 字典类型ID列表
   */
  const batchRemoveType = async (ids: string[]) => {
    try {
      const res = await batchDeleteDictType(ids)
      
      if (res.code === 200) {
        message.success(t('common.batchDeleteSuccess'))
        fetchTypeList()
        return true
      } else {
        message.error(res.message || t('common.batchDeleteFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.batchDeleteFailed'))
      return false
    }
  }

  /**
   * 导出字典类型
   */
  const exportType = async () => {
    try {
      const blob = await exportDictType()
      if (blob instanceof Blob) {
        // 处理导出文件
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `dict_type_${new Date().getTime()}.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)
        message.success(t('common.exportSuccess'))
        return true
      } else {
        message.error(t('common.exportFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.exportFailed'))
      return false
    }
  }

  /**
   * 打开字典类型表单弹窗
   * @param id 字典类型ID，不传为新增
   */
  const openTypeModal = async (id?: string) => {
    // 重置表单
    resetTypeForm()
    
    if (id) {
      currentTypeId.value = id
      await fetchTypeDetail(id)
    } else {
      typeFormMode.value = 'add'
      typeModalVisible.value = true
    }
  }

  /**
   * 重置字典类型表单
   */
  const resetTypeForm = () => {
    typeFormData.dictName = ''
    typeFormData.dictType = ''
    typeFormData.status = '0'
    typeFormData.remark = ''
    
    // 确保id被移除
    const form = typeFormData as any
    if (form.id) {
      delete form.id
    }
  }

  /**
   * 重置字典类型查询参数
   */
  const resetTypeQuery = () => {
    typeQueryParams.dictName = ''
    typeQueryParams.dictType = ''
    typeQueryParams.status = undefined
    createTimeRange.value = undefined
    
    // 保持页码为1，保持每页条数不变
    typeQueryParams.pageNum = 1
  }

  /**
   * 处理字典类型页码变化
   * @param page 页码
   * @param pageSize 每页条数
   */
  const handleTypePageChange = (page: number, pageSize?: number) => {
    typeQueryParams.pageNum = page
    if (pageSize) {
      typeQueryParams.pageSize = pageSize
    }
    typePagination.current = page
    if (pageSize) {
      typePagination.pageSize = pageSize
    }
    fetchTypeList()
  }

  // ------------ 字典数据方法 ------------
  /**
   * 获取字典数据列表
   */
  const fetchDataList = async () => {
    if (!currentDictType.value) {
      message.warning(t('dict.selectTypeFirst'))
      return
    }
    
    try {
      dataLoading.value = true
      
      // 更新查询参数中的字典类型
      dataQueryParams.dictType = currentDictType.value
      
      const res = await getDictDataPage(dataQueryParams)
      
      if (res.code === 200) {
        dataList.value = res.data.list
        dataPagination.total = res.data.total
      } else {
        message.error(res.message || t('dict.loadFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
    } finally {
      dataLoading.value = false
    }
  }

  /**
   * 获取字典数据详情
   * @param id 字典数据ID
   */
  const fetchDataDetail = async (id: string) => {
    try {
      const res = await getDictDataDetail(id)
      
      if (res.code === 200) {
        Object.assign(dataFormData, res.data)
        dataFormMode.value = 'edit'
        dataModalVisible.value = true
      } else {
        message.error(res.message || t('dict.detailFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchDetailFailed'))
    }
  }

  /**
   * 提交字典数据表单
   */
  const submitDataForm = async () => {
    dataSubmitLoading.value = true
    try {
      let result
      if (dataFormMode.value === 'add') {
        result = await createDictData(dataFormData)
      } else {
        // 编辑模式需要添加id属性，转为UpdateDictData类型
        const updateData: UpdateDictData = {
          ...dataFormData,
          id: currentDataId.value
        }
        result = await updateDictData(currentDataId.value, updateData)
      }
      
      if (result.code === 200) {
        message.success(dataFormMode.value === 'add' ? t('common.createSuccess') : t('common.updateSuccess'))
        dataModalVisible.value = false
        await fetchDataList()
        return true
      } else {
        message.error(result.message || t('common.operationFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.operationFailed'))
      return false
    } finally {
      dataSubmitLoading.value = false
    }
  }

  /**
   * 删除字典数据
   * @param id 字典数据ID
   */
  const removeData = async (id: string) => {
    try {
      const res = await deleteDictData(id)
      
      if (res.code === 200) {
        message.success(t('common.deleteSuccess'))
        fetchDataList()
        return true
      } else {
        message.error(res.message || t('common.deleteFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.deleteFailed'))
      return false
    }
  }

  /**
   * 批量删除字典数据
   * @param ids 字典数据ID列表
   */
  const batchRemoveData = async (ids: string[]) => {
    try {
      const res = await batchDeleteDictData(ids)
      
      if (res.code === 200) {
        message.success(t('common.batchDeleteSuccess'))
        fetchDataList()
        return true
      } else {
        message.error(res.message || t('common.batchDeleteFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.batchDeleteFailed'))
      return false
    }
  }

  /**
   * 打开字典数据表单弹窗
   * @param id 字典数据ID，不传为新增
   */
  const openDataModal = async (id?: string) => {
    // 重置表单
    resetDataForm()
    
    if (id) {
      currentDataId.value = id
      await fetchDataDetail(id)
    } else {
      // 设置字典类型
      dataFormData.dictType = currentDictType.value
      dataFormMode.value = 'add'
      dataModalVisible.value = true
    }
  }

  /**
   * 重置字典数据表单
   */
  const resetDataForm = () => {
    dataFormData.dictType = currentDictType.value
    dataFormData.dictLabel = ''
    dataFormData.dictValue = ''
    dataFormData.dictSort = 0
    dataFormData.status = '0'
    dataFormData.cssClass = ''
    dataFormData.remark = ''
    
    // 确保id被移除
    const form = dataFormData as any
    if (form.id) {
      delete form.id
    }
  }

  /**
   * 重置字典数据查询参数
   */
  const resetDataQuery = () => {
    dataQueryParams.dictLabel = ''
    dataQueryParams.dictValue = ''
    dataQueryParams.status = undefined
    
    // 保持字典类型不变
    dataQueryParams.dictType = currentDictType.value
    
    // 保持页码为1，保持每页条数不变
    dataQueryParams.pageNum = 1
  }

  /**
   * 处理字典数据页码变化
   * @param page 页码
   * @param pageSize 每页条数
   */
  const handleDataPageChange = (page: number, pageSize?: number) => {
    dataQueryParams.pageNum = page
    if (pageSize) {
      dataQueryParams.pageSize = pageSize
    }
    dataPagination.current = page
    if (pageSize) {
      dataPagination.pageSize = pageSize
    }
    fetchDataList()
  }

  /**
   * 设置当前字典类型并加载其数据
   * @param dictType 字典类型标识
   * @param dictName 字典类型名称
   */
  const setCurrentType = async (dictType: string, dictName: string) => {
    currentDictType.value = dictType
    currentDictTypeName.value = dictName
    
    // 更新查询参数
    dataQueryParams.dictType = dictType
    dataQueryParams.pageNum = 1
    
    // 加载字典数据
    await fetchDataList()
  }

  // 返回store中的状态和方法
  return {
    // 基础状态
    currentDictType,
    currentDictTypeName,
    currentTypeId,
    currentDataId,
    
    // 加载状态
    typeLoading,
    typeSubmitLoading,
    dataLoading,
    dataSubmitLoading,
    
    // 字典类型状态
    typeList,
    typePagination,
    typeQueryParams,
    createTimeRange,
    typeModalVisible,
    typeFormData,
    typeFormMode,
    typeFormTitle,
    
    // 字典数据状态
    dataList,
    dataPagination,
    dataQueryParams,
    dataModalVisible,
    dataFormData,
    dataFormMode,
    dataFormTitle,
    
    // 字典类型方法
    fetchTypeList,
    fetchTypeDetail,
    submitTypeForm,
    removeType,
    batchRemoveType,
    exportType,
    openTypeModal,
    resetTypeForm,
    resetTypeQuery,
    handleTypePageChange,
    
    // 字典数据方法
    fetchDataList,
    fetchDataDetail,
    submitDataForm,
    removeData,
    batchRemoveData,
    openDataModal,
    resetDataForm,
    resetDataQuery,
    handleDataPageChange,
    setCurrentType
  }
}) 